<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Sidebar;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 客户详情.
 * @Controller
 */
class EmployeeContact extends AbstractAction
{
    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeContract;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactContract;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/workContact/employeeContact", methods="GET")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        $contacts = $this->workContactEmployeeContract->getWorkContactEmployeeByCorpIdEmployeeId($user['id'], $user['corpId'], ['contact_id']);
        if (empty($contacts)) {
            return [];
        }
        $contactIds = array_column($contacts, 'contactId');
        $list = $this->workContactContract->getWorkContactsById($contactIds, ['name', 'avatar', 'wx_external_userid']);
        foreach ($list as $k => $v) {
            $list[$k]['avatar'] = file_full_url($v['avatar']);
        }

        return $list;
    }
}
